package cn.diancan.util;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtil {
    
    public static Map<String,String[]> hostMap =new HashMap<String ,String[]>();
    public static String DEFAULT_CHARSET="GBK"; 
    public static String HTML_TYPE="text/html";
    public static String TEXT_TYPE="text/plain";
    
    
    static{
	hostMap.put("163.com", new String[]{"stmp","smtp.163.com"}); 
    } 
    
    public static void main(String[] args) {
	try {
	    sendMail("sf12445@163.com", "q7656606123", "Bug中心", "baopiqi@vip.qq.com", "您的应用有问题", "<table>受什么呢 </div>");
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
    
    public static boolean sendMail( String name, String subject,String content ) throws Exception{
	 
	Setting setting = SettingUtils.getCommonSetting();
	
	String recipients = setting.getNotify_mail_recipients();
	String[] sr =recipients.split(",");
	for (int i = 0; i < sr.length; i++) {
	    sendMail(setting.getNotify_mail_smtp_host(), setting.getNotify_mail_transport_protocol(),
			setting.getNotify_mail_account(), setting.getNotify_mail_password(),
			name, sr[i], subject, content, setting.getNotify_mail_charset());
	}
	return true;
    }
    
    
    public static boolean sendMail(String host,String protocol, String from,String pass,String name,String to,String subject,String content,String charSet) throws Exception{
	//声明主机名和发送邮件的地址   
            
        // 设定所要用的Mail 服务器和所使用的传输协议
        Properties pro = System.getProperties();
        pro.put("mail.smtp.host", host);             //设定了使用的mail服务器
        pro.put("mail.transport.protocol", protocol);  //设定了服务器使用的协议
        pro.put("mail.smtp.auth", "true");           //指定是否需要smtp验证
        
        //验证是否通过
    //    Authenticator  auth = new MyAuthenticator();
        Authenticator  auth = new Authenticator() { 
			@Override
			protected PasswordAuthentication getPasswordAuthentication() { 
				return super.getPasswordAuthentication();
			} 
	};
       //得到新的session服务
        javax.mail.Session mailSession = javax.mail.Session.getDefaultInstance(pro, auth);
        
        //定义邮件内容
        MimeMessage message = new MimeMessage(mailSession);
        try {
            message.setContent(content, HTML_TYPE+";charset="+charSet);     //如果    message所使用的内容是文本的话，那么可以使用message.setContent（‘hello’）来直接传入值
            
            //设定主题
            message.setSubject(subject); 
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        //设置邮件的地址类，使用Address的InternetAddress子类 ,可以通过传递两个参数：代表邮件地址和名字的字符串来建立一个具有邮件地址和名字的邮件地址类
        try {
            Address address = new InternetAddress(from,name);     //设定发送者姓名 
            
            //设置邮件的发信人
            message.setFrom(address);        
            //或者message.setReplyTo(address);如果在邮件中存在多个发信人地址，我们可用addForm()方法增加发信人，Address address[] = ...;            message.addFrom(address);  
            
            //设置邮件的收信人
            Address toAddress = new InternetAddress(to); 
            
            //设置的时候有三个常量，Message.RecipientType.TO,Message.RecipientType.CC,Message.RecipientType.BCC,来指定邮件接收人首要发送人、抄送人、秘密抄送人
            message.addRecipient(Message.RecipientType.TO, toAddress); 
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        try {
             //设定邮箱的代理服务器
            Transport transport = mailSession.getTransport("smtp");
            //填写上发送者邮箱的账号和密码，和使用的mail服务器
            transport.connect(host, from, pass);
            //执行发送邮件任务
             transport.sendMessage(message,message.getAllRecipients());
            //关闭
             transport.close();  
             return true;
        } catch (NoSuchProviderException e) { 
            e.printStackTrace();
        } catch (MessagingException e) { 
            System.out.println("您的用户名和密码不正确");
        } 
        return false;
    }
    
    
    private static boolean sendMail(String from,String pass,String name,String to,String subject,String content) throws Exception{
	return  sendMail(from, pass, name, to, subject, content,DEFAULT_CHARSET);
    }
    
    
    private static boolean sendMail(String from,String pass,String name,String to,String subject,String content,String charSet) throws Exception{
	//声明主机名和发送邮件的地址  
        String host = "";        //所使用的mail服务器
        //String from = "sf12445@163.com";                    //发件人地址
        //String to = "songya1007@sina.cn";                      //收件人地址
        if(null == host || "".equals(host)){
            try {
        	String[] m= hostMap.get(from.split("@")[1]);
        	if(null!=m){ 
        	    host =m[1];
        	}
            } catch (Exception e1) { 
        	e1.printStackTrace();
            }
        }
        
        if(null == host || "".equals(host)){
            return false;
        }
            
        // 设定所要用的Mail 服务器和所使用的传输协议
        Properties pro = System.getProperties();
        pro.put("mail.smtp.host", host);             //设定了使用的mail服务器
        pro.put("mail.transport.protocol", "smtp");  //设定了服务器使用的协议
        pro.put("mail.smtp.auth", "true");           //指定是否需要smtp验证
        
        //验证是否通过
    //    Authenticator  auth = new MyAuthenticator();
        Authenticator  auth = new Authenticator() { 
			@Override
			protected PasswordAuthentication getPasswordAuthentication() { 
				return super.getPasswordAuthentication();
			} 
	};
       //得到新的session服务
        javax.mail.Session mailSession = javax.mail.Session.getDefaultInstance(pro, auth);
        
        //定义邮件内容
        MimeMessage message = new MimeMessage(mailSession);
        try {
            message.setContent(content, HTML_TYPE+";charset="+charSet);     //如果    message所使用的内容是文本的话，那么可以使用message.setContent（‘hello’）来直接传入值
            
            //设定主题
            message.setSubject(subject); 
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        //设置邮件的地址类，使用Address的InternetAddress子类 ,可以通过传递两个参数：代表邮件地址和名字的字符串来建立一个具有邮件地址和名字的邮件地址类
        try {
            Address address = new InternetAddress(from,name);     //设定发送者姓名 
            
            //设置邮件的发信人
            message.setFrom(address);        
            //或者message.setReplyTo(address);如果在邮件中存在多个发信人地址，我们可用addForm()方法增加发信人，Address address[] = ...;            message.addFrom(address);  
            
            //设置邮件的收信人
            Address toAddress = new InternetAddress(to); 
            
            //设置的时候有三个常量，Message.RecipientType.TO,Message.RecipientType.CC,Message.RecipientType.BCC,来指定邮件接收人首要发送人、抄送人、秘密抄送人
            message.addRecipient(Message.RecipientType.TO, toAddress); 
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        try {
             //设定邮箱的代理服务器
            Transport transport = mailSession.getTransport("smtp");
            //填写上发送者邮箱的账号和密码，和使用的mail服务器
            transport.connect(host, from, pass);
            //执行发送邮件任务
             transport.sendMessage(message,message.getAllRecipients());
            //关闭
             transport.close();  
             return true;
        } catch (NoSuchProviderException e) { 
            e.printStackTrace();
        } catch (MessagingException e) { 
            System.out.println("您的用户名和密码不正确");
        } 
        return false;
    }
    
    

}
